angular.module('tab-order-list', [])

.controller 'TabOrderListCtrl', (Toast,$location, $localStorage, $ionicLoading, $scope, $state,$http, $window, $ionicHistory,$stateParams, orderService, ListDataService, $ionicScrollDelegate,$filter) ->
  orderListSrv = ListDataService.get('orderList')
  orderListSrv.watch (orderDatas) ->
    $scope.orderList = orderDatas
#  orderListSrv.reload({history: 0}, true).finally ->
#    console.log 'load end'
#    $scope.$broadcast 'scroll.refreshComplete'

  _.extend $scope,
    selectTap: 0
    orderList:[]
    lishi:false
    dangqian:true


    clickqhl: ->
      $scope.selectTap = 0
      $scope.lishi=false
      $scope.dangqian=true
      $scope.doRefresh()

    clickqhr: ->
      $scope.selectTap = 1
      $scope.lishi=true
      $scope.dangqian=false
      $scope.doRefresh()

    goDetail: (orderId) ->
      $state.go('tab.orderDetail', {id: orderId})
    goPay: (orderId) ->
      $state.go('tab.pay',{id: orderId})

    canLoadMore: () ->
      console.log(orderListSrv.canLoadMore())
      orderListSrv.canLoadMore()

    doRefresh: ->
      console.log 'reload'
      orderListSrv.reload({history: $scope.selectTap}, true).finally ->
        console.log 'load end'
        $scope.$broadcast 'scroll.refreshComplete'

    loadMore: ->
      console.log 'loadMore'
      orderListSrv.loadMore({history: $scope.selectTap}, true).finally -> $scope.$broadcast 'scroll.infiniteScrollComplete'

    # 提前终止订单
    ahead: (id) ->
      orderService.ahead(id).then(->
        orderListSrv.reload({history: $scope.selectTap}, false).finally ->
          console.log 'load end'
          $scope.$broadcast 'scroll.refreshComplete'
      )

    #取消订单
    cancel: (id) ->
      orderService.cancel(id).then(->
        orderListSrv.reload({history: $scope.selectTap}, false).finally ->
          console.log 'load end'
          $scope.$broadcast 'scroll.refreshComplete'
      )
    paiban:(id)->
      $http.post('/schedule',{crewId:1,orderId:id})
      .success (resp) ->
        if resp.code==0
          Toast.showMsg('排班成功')
          orderListSrv.reload({history: $scope.selectTap}, true)
        else
          Toast.showMsg('排班失败')
      .error (resp, status) ->
        Toast.showBusinessError(resp.message)
  $scope.clickqhl()